#include "bstrings.h"
#include <algorithm>

using namespace butils;

std::vector<std::string> strings::split(std::string src, char par)
{
    std::vector<std::string> des;
    auto pos = src.find(par);
    while (pos != std::string::npos)
    {
        des.emplace_back(src.substr(0, pos));
        src.erase(0, pos + 1);
        pos = src.find(par);
    }
    if (src.size() != 0)
    {
        des.emplace_back(src);
    }
    return des;
}

bool strings::split(const std::string& str, const std::string& sep, std::string* pleft, std::string* pright)
{
    size_t pos = str.find(sep);
    std::string left, right;
    if (pos != std::string::npos) {
        left = std::string(str, 0, pos);
        right = std::string(str, pos + 1);

        trim(left);
        trim(right);

        *pleft = left;
        *pright = right;
        return true;
    }
    else {
        left = str;
        right = "";

        trim(left);

        *pleft = left;
        *pright = right;
        return false;
    }
}

bool strings::compare_ingore_case(const std::string& str1, const std::string& str2)
{
    std::string a = str1;
    std::string b = str2;
    transform(a.begin(), a.end(), a.begin(), ::toupper);
    transform(b.begin(), b.end(), b.begin(), ::toupper);
    return (a == b);
}

bool strings::start_with(const std::string& str, const std::string& prefix)
{
    return strncmp(str.c_str(), prefix.c_str(), prefix.size()) == 0;
}

bool strings::end_with(const std::string& str, const std::string& suffix)
{
    if (str.length() > suffix.length()) {
        return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
    }
    return false;
}

void strings::trim(std::string& str)
{
    if (!str.empty()) {
        str.erase(0, str.find_first_not_of(" \r\n\t"));
        str.erase(str.find_last_not_of(" \r\n\t") + 1);
    }
}

std::string strings::strip(const std::string& str)
{
    std::string nstr(str);
    trim(nstr);
    return nstr;
}
